package dragon.modules.system.menu.intercept;

import java.util.Map;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

import dragon.core.db.DML;
import dragon.core.exception.ExceptionHandler;
import dragon.core.system.po.SysMenu;
import dragon.core.system.po.SysRoleMenu;
import dragon.core.util.StringUtils;
import dragon.model.bizObject.BizObject;
import dragon.model.intercept.Interceptor;
import dragon.modules.system.menu.dao.MenuDaoImpl;
import ejp.Database;
import ejw.ServerInterface;

/**
 * 实现功能：MENU拦截器
 */
public class MenuInterceptor extends Interceptor {

	@Override
	public int beforeAdd(BizObject bizObject, Map<String, String> parameterMap, ServerInterface sif, Database db) throws ExceptionHandler {
		if (StringUtils.isEmpty(parameterMap.get("PID"))) {
			parameterMap.put("PID", "0");
			parameterMap.put("IDPATH", "/" + parameterMap.get("ID") + "/");
		} else {
			MenuDaoImpl md = new MenuDaoImpl();
			SysMenu parent = md.get(db, Integer.parseInt(parameterMap.get("PID")));

			parameterMap.put("IDPATH", parent.getIdpath() + parameterMap.get("ID") + "/");

			parent = null;
			md = null;
		}
		return INCLUDE_ALL;
	}

	@Override
	public int beforeDel(BizObject bizObject, Map<String, String> parameterMap, ServerInterface sif, Database db) throws ExceptionHandler {
		try {
			JSONArray rows = (JSONArray) new JSONParser().parse(parameterMap.get("rows"));
			JSONObject jsonObj = null;
			for (Object obj : rows) {
				jsonObj = (JSONObject) obj;
				String id = jsonObj.get("ID").toString();
				// 修改涉及到的菜单角色关联表
				DML.executeUpdate("delete from " + SysRoleMenu.tableName + " where menu=" + id);
				// 删除部门(包含其子级节点数据)
				DML.executeUpdate("delete from " + SysMenu.tableName + " where id=" + id + " or idpath like '%/" + id + "/%'");
			}
			jsonObj = null;
			rows = null;
		} catch (ParseException e) {
			throw new ExceptionHandler(e);
		}
		return EXCLUDE_ALL;
	}

}
